<template>
  <div class="menus-page">
    <div class="page-header">
      <h2>菜单管理</h2>
      <el-button type="primary" @click="showAddDialog = true">
        <el-icon><Plus /></el-icon>
        添加菜单
      </el-button>
    </div>

    <!-- 菜单树 -->
    <el-card>
      <el-table
        :data="menuTree"
        v-loading="loading"
        style="width: 100%"
        row-key="id"
        :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
      >
        <el-table-column prop="name" label="菜单名称" />
        <el-table-column prop="path" label="路径" />
        <el-table-column prop="component" label="组件" />
        <el-table-column prop="icon" label="图标">
          <template #default="{ row }">
            <el-icon v-if="row.icon">
              <component :is="row.icon" />
            </el-icon>
            <span v-else>-</span>
          </template>
        </el-table-column>
        <el-table-column prop="sort_order" label="排序" width="80" />
        <el-table-column prop="is_active" label="状态" width="80">
          <template #default="{ row }">
            <el-tag :type="row.is_active ? 'success' : 'danger'">
              {{ row.is_active ? '启用' : '禁用' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="300">
          <template #default="{ row }">
            <el-button size="small" @click="addSubMenu(row)">添加子菜单</el-button>
            <el-button size="small" type="primary" @click="editMenu(row)">编辑</el-button>
            <el-button size="small" type="danger" @click="deleteMenu(row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 添加/编辑菜单对话框 -->
    <el-dialog
      v-model="showAddDialog"
      :title="editingMenu ? '编辑菜单' : '添加菜单'"
      width="600px"
    >
      <el-form
        ref="menuFormRef"
        :model="menuForm"
        :rules="menuRules"
        label-width="100px"
      >
        <el-form-item label="菜单名称" prop="name">
          <el-input v-model="menuForm.name" placeholder="请输入菜单名称" />
        </el-form-item>
        <el-form-item label="路径" prop="path">
          <el-input v-model="menuForm.path" placeholder="请输入路径" />
        </el-form-item>
        <el-form-item label="组件" prop="component">
          <el-input v-model="menuForm.component" placeholder="请输入组件路径" />
        </el-form-item>
        <el-form-item label="图标" prop="icon">
          <el-input v-model="menuForm.icon" placeholder="请输入图标名称" />
        </el-form-item>
        <el-form-item label="父菜单" prop="parent">
          <el-tree-select
            v-model="menuForm.parent"
            :data="parentMenuOptions"
            :props="{ value: 'id', label: 'name', children: 'children' }"
            placeholder="请选择父菜单"
            clearable
            check-strictly
          />
        </el-form-item>
        <el-form-item label="排序" prop="sort_order">
          <el-input-number v-model="menuForm.sort_order" :min="0" />
        </el-form-item>
        <el-form-item label="状态" prop="is_active">
          <el-switch v-model="menuForm.is_active" />
        </el-form-item>
      </el-form>

      <template #footer>
        <el-button @click="showAddDialog = false">取消</el-button>
        <el-button type="primary" @click="saveMenu" :loading="saving">
          {{ editingMenu ? '更新' : '创建' }}
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
import { userManagementAPI } from '@/api/userManagement'

// 响应式数据
const loading = ref(false)
const saving = ref(false)
const menuTree = ref([])
const allMenus = ref([])

// 对话框控制
const showAddDialog = ref(false)
const editingMenu = ref(null)
const parentMenu = ref(null)

// 菜单表单
const menuForm = reactive({
  name: '',
  path: '',
  component: '',
  icon: '',
  parent: null,
  sort_order: 0,
  is_active: true
})

// 表单引用
const menuFormRef = ref()

// 计算属性
const parentMenuOptions = computed(() => {
  const buildOptions = (menus, level = 0) => {
    return menus.map(menu => ({
      id: menu.id,
      name: '　'.repeat(level) + menu.name,
      children: menu.children ? buildOptions(menu.children, level + 1) : []
    }))
  }
  return buildOptions(menuTree.value)
})

// 表单验证规则
const menuRules = {
  name: [
    { required: true, message: '请输入菜单名称', trigger: 'blur' },
    { min: 2, max: 100, message: '菜单名称长度在 2 到 100 个字符', trigger: 'blur' }
  ],
  path: [
    { required: true, message: '请输入路径', trigger: 'blur' }
  ]
}

// 方法
const loadMenus = async () => {
  loading.value = true
  try {
    const response = await userManagementAPI.getMenuTree()
    menuTree.value = response

    // 同时获取所有菜单的平铺列表
    const allResponse = await userManagementAPI.getMenus()
    allMenus.value = allResponse.results || allResponse
  } catch (error) {
    console.error('加载菜单失败:', error)
    ElMessage.error('加载菜单失败')
  } finally {
    loading.value = false
  }
}

const addSubMenu = (parentMenuData) => {
  parentMenu.value = parentMenuData
  menuForm.parent = parentMenuData.id
  showAddDialog.value = true
}

const editMenu = (menu) => {
  editingMenu.value = menu
  menuForm.name = menu.name
  menuForm.path = menu.path
  menuForm.component = menu.component
  menuForm.icon = menu.icon
  menuForm.parent = menu.parent
  menuForm.sort_order = menu.sort_order
  menuForm.is_active = menu.is_active
  showAddDialog.value = true
}

const saveMenu = async () => {
  if (!menuFormRef.value) return

  try {
    await menuFormRef.value.validate()
    saving.value = true

    if (editingMenu.value) {
      await userManagementAPI.updateMenu(editingMenu.value.id, menuForm)
      ElMessage.success('菜单更新成功')
    } else {
      await userManagementAPI.createMenu(menuForm)
      ElMessage.success('菜单创建成功')
    }

    showAddDialog.value = false
    resetForm()
    loadMenus()
  } catch (error) {
    console.error('保存菜单失败:', error)
    ElMessage.error('保存菜单失败')
  } finally {
    saving.value = false
  }
}

const deleteMenu = async (menu) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除菜单 "${menu.name}" 吗？删除后其子菜单也会被删除。`,
      '确认删除',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )

    await userManagementAPI.deleteMenu(menu.id)
    ElMessage.success('菜单删除成功')
    loadMenus()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除菜单失败:', error)
      ElMessage.error('删除菜单失败')
    }
  }
}

const resetForm = () => {
  menuForm.name = ''
  menuForm.path = ''
  menuForm.component = ''
  menuForm.icon = ''
  menuForm.parent = null
  menuForm.sort_order = 0
  menuForm.is_active = true
  editingMenu.value = null
  parentMenu.value = null
  if (menuFormRef.value) {
    menuFormRef.value.resetFields()
  }
}

// 生命周期
onMounted(() => {
  loadMenus()
})
</script>

<style scoped>
.menus-page {
  padding: 20px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.page-header h2 {
  margin: 0;
  color: #303133;
}
</style>
